package com.maycurobj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.maycurobj.pojo.MayCurCallback;
import com.maycurobj.repository.bim.TbtaccRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 每刻 待办业务处理服务
 */
@Service
@Slf4j
public class MaycurTodoServiceImpl {

    @Autowired
    private TbtaccRepository repository;

    //IAM 请求url  正式的外网地址: 221.12.6.180:18189
    private String URL = "http://172.16.10.198:8081/bim-server/api/rest/integration";

    /**
     * 处理 iam 待办
     */
    public String proccessIamTodo(MayCurCallback entity) {
        //获取token
        String token = getToken();

        List<String> usernames = new ArrayList<>();

        //根据工号 转化为 需要推送的crmuser 信息
        for (String s : entity.getTaskAssignee()) {
            String username = getUsername(s);
            if (StringUtils.isNotBlank(username)) {
                usernames.add(username);
            }
        }

        //类型
        String taskActionType = entity.getTaskActionType();
        //事件场景
        String eventScenario = entity.getEventScenario();

        for (String s : usernames) {

            //条件判断 新建待办
            if (taskActionType.equals("PROCESSING")) {
                //推送 新待办
                reqIamTodoAdd(token, entity, s);
            } else if (taskActionType.equals("COMPLETED") || taskActionType.equals("REMOVED") || taskActionType.equals("REJECTED") || taskActionType.equals("RECALLED")) {
                //禁用 待办
                reaIamTodoDisable(token, entity.getTaskId());
            }

        }

        //释放token
        outToken(token);
        return "done";
    }

    /**
     * 获取crm username 通过工号
     *
     * @param s
     * @return
     */
    private String getUsername(String s) {
        try {
            String ret = repository.getCrmUsernameByWorkcode(s);
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }

    //请求 IAM增加 待办
    private void reqIamTodoAdd(String token, MayCurCallback obj, String username) {
        //推送 count 次数
        JSONObject entity = new JSONObject();
        entity.put("name", obj.getFormType());
        entity.put("code", obj.getTaskId());
        entity.put("backlogtype", "3");
        entity.put("crmuser", username);
        entity.put("backlogurl", "https://ng.maycur.com");
        JSONObject reqJet = new JSONObject();
        reqJet.put("token", token);
        reqJet.put("objectCode", "biosanCrmRes");
        reqJet.put("entity", entity);
        String url = URL + "/ExtApiIngtTargetResourceService/add";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(reqJet, headers);
        JSONObject retJson = restTemplate.postForObject(url, httpEntity, JSONObject.class);

        log.info("用户{}推送完成,结果--->{}", JSONObject.toJSONString(retJson));
    }

    //请求 IAM待办 禁用
    private void reaIamTodoDisable(String token, String code) {
        String url = URL + "/ExtApiIngtTargetResourceService/disableByCode";
        JSONObject entity = new JSONObject();
        entity.put("token", token);
        entity.put("objectCode", "biosanCrmRes");
        entity.put("code", code);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(entity, headers);
        JSONObject retJson = restTemplate.postForObject(url, httpEntity, JSONObject.class);
        log.info("禁用待办完成,结果------>{}", JSONObject.toJSONString(retJson));
    }

    /**
     * 获取iam token
     *
     * @return
     */
    private String getToken() {
        String url = URL + "/ExtApiIngtAuthService/login?systemCode=biosanCrm&integrationKey=password&force=false&clientId=biosanCrm";
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(null, headers);
        JSONObject retJson = restTemplate.postForObject(url, httpEntity, JSONObject.class);
        log.info("打印下retJson------->{}", JSONObject.toJSONString(retJson));
        return retJson.getString("data");
    }

    /**
     * 释放 iam token
     *
     * @param token
     */
    private void outToken(String token) {
        String url = URL + "/ExtApiIngtAuthService/logout?token=" + token;
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(null, headers);
        JSONObject retJson = restTemplate.postForObject(url, httpEntity, JSONObject.class);
        log.info("iamtoken释放结果------->{}", JSONObject.toJSONString(retJson));
    }
}
